﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.BackgroundAudio;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Xna.Framework.Media;
namespace TruyenAudio
{
    public partial class MediaPlay : PhoneApplicationPage
    {
        bool settingSliderFromPlay;
        ApplicationBarIconButton btnPlay;
        ProgressIndicator progressIndicator;
        Random rd = new Random();


        public MediaPlay()
        {
            InitializeComponent();

            TenTruyen.Text = "Audio Truyện";
            tapTruyen.Text = ListItem.Taptruyen.ToString();

            InitUrlAudio();
            BuildLocalizedApplicationBar();
            //random hinh nen chay nhac
            int so = rd.Next(1, 6);

            imageview.Source = new BitmapImage(new Uri("/images/Music/music" + so.ToString() + ".png", UriKind.Relative));
            //chay nhac luon
            if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
            {
                BackgroundAudioPlayer.Instance.Pause();
                btnPlay.IconUri = new Uri("/images/play.png", UriKind.Relative);
                btnPlay.Text = "Play";
            }
            else
            {
                progressIndicator = new ProgressIndicator()
                {

                    IsVisible = true,
                    IsIndeterminate = false,

                    Text = "Loading …"
                };
                SystemTray.SetProgressIndicator(this, progressIndicator);
                try
                {
                    BackgroundAudioPlayer.Instance.Play();
                    btnPlay.IconUri = new Uri("/images/Pause.png", UriKind.Relative);
                    btnPlay.Text = "Pause";
                }
                catch (Exception)
                {

                    MessageBox.Show("Loi MediaPlay.KhoiTao");
                }
               
            }

            CompositionTarget.Rendering += CompositionTarget_Rendering;


            //RATE APP
            // Rate apps
            FeedbackOverlay.VisibilityChanged += FeedbackOverlay_VisibilityChanged;
        }

        private void FeedbackOverlay_VisibilityChanged(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
        }

        private void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            AudioTrack audioTrack = null;
            TimeSpan position = TimeSpan.Zero;
            TimeSpan duration = TimeSpan.Zero;

            try
            {
                // Sometimes these property accesses will raise exceptions
                audioTrack = BackgroundAudioPlayer.Instance.Track;

                if (audioTrack != null)
                {
                    duration = audioTrack.Duration;
                    position = BackgroundAudioPlayer.Instance.Position;
                }
            }
            catch
            {
            }

            if (audioTrack != null)
            {
                elapsedDuration.Text = position.ToString("m\\:ss");
                totalDuration.Text = duration.ToString("m\\:ss");
                if (!elapsedDuration.Text.Equals("0:00"))
                {
                    progressIndicator.IsVisible = false;
                }
                // Change the Slider position, but set a flag to 
                //  avoid the ValueChanged handler from being confused.
                settingSliderFromPlay = true;

                if (duration.Ticks > 0)
                    positionSlider.Value = (double)position.Ticks / duration.Ticks;
                else
                    positionSlider.Value = 0;

                settingSliderFromPlay = false;
            }
            else
            {
                elapsedDuration.Text = null;
                totalDuration.Text = null;
                positionSlider.Value = 0;
            }
        }


        private void BuildLocalizedApplicationBar()
        {
            // Set the page's ApplicationBar to a new instance of ApplicationBar.
            ApplicationBar = new ApplicationBar();
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = true;
            // Create a new button and set the text value to the localized string from AppResources.

            btnPlay = new ApplicationBarIconButton(new Uri("/images/pause.png", UriKind.Relative));
            btnPlay.Text = "Pause";

            ApplicationBar.Buttons.Add(btnPlay);


            //su kien
            btnPlay.Click += new EventHandler(btnPlay_Click);
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
            {
                BackgroundAudioPlayer.Instance.Pause();
                btnPlay.IconUri = new Uri("/images/play.png", UriKind.Relative);
                btnPlay.Text = "Play";
            }
            else
            {
                BackgroundAudioPlayer.Instance.Play();
                btnPlay.IconUri = new Uri("/images/Pause.png", UriKind.Relative);
                btnPlay.Text = "Pause";
            }
        }

      
       

        //play nhac
        public void InitUrlAudio()
        {
            try
            {
                BackgroundAudioPlayer.Instance.Track = new AudioTrack(new Uri(ListItem.LinkTruyen, UriKind.Absolute),
                               ListItem.Taptruyen
,
                              "",
                               "",
                               null);
            }
            catch (Exception)
            {

                MessageBox.Show("Không khởi tạo được Track Audio");
            }
           
        }

        private void positionSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
           if (!settingSliderFromPlay)
            {
                AudioTrack audioTrack = null;
                TimeSpan duration = TimeSpan.Zero;

                try
                {
                    // Sometimes these property accesses will raise exceptions
                    audioTrack = BackgroundAudioPlayer.Instance.Track;

                    if (audioTrack != null)
                        duration = audioTrack.Duration;
                }
                catch
                {
                }

                if (audioTrack == null)
                    return;

                long ticks = (long)(e.NewValue * duration.Ticks);
                BackgroundAudioPlayer.Instance.Position = new TimeSpan(ticks);
            }
        }


        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult kq = MessageBox.Show("Truyện sẽ bị tắt. Bạn muốn quay lại?", "Thông Báo", MessageBoxButton.OKCancel);
            if (kq == MessageBoxResult.OK)
            {
               // ((App)Application.Current).RootFrame.Navigate(new Uri("/TapTruyen.xaml", UriKind.Relative));
                BackgroundAudioPlayer.Instance.Close();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void positionSlider_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
        }
    }
}